package com.ry.demo.register.client;

import com.ry.demo.register.client.dto.HttpSender;
import com.ry.demo.register.client.dto.RegisterRequest;
import com.ry.demo.register.client.dto.RegisterResponse;

/**
 * @Author: lihui
 * @Date: 2021-12-01 10:49
 * @Description: 注册的工作线程
 */
public class RegisterClientWorker implements Runnable {

    public static final String SERVICE_NAME = "inventory-service";
    public static final String IP = "192.168.31.207";
    public static final String HOSTNAME = "inventory01";
    public static final int PORT = 9000;

    /**
     * 服务实例id
     */
    private String serviceInstanceId;

    /**
     * http请求组件
     */
    private HttpSender httpSender;


    public RegisterClientWorker(String serviceInstanceId, HttpSender httpSender) {
        this.serviceInstanceId = serviceInstanceId;
        this.httpSender = httpSender;
    }

    @Override
    public void run() {
        RegisterRequest registerRequest = new RegisterRequest();
        registerRequest.setServiceName(SERVICE_NAME);
        registerRequest.setIp(IP);
        registerRequest.setHostname(HOSTNAME);
        registerRequest.setPort(PORT);
        registerRequest.setServiceInstanceId(serviceInstanceId);
        RegisterResponse registerResponse = httpSender.register(registerRequest);

        // 如果注册失败的话
        if(RegisterResponse.FAILURE.equals(registerResponse.getStatus())) {
            return;
        }

        // 如果注册成功的话，启动发送心跳工作线程
        new Thread(new HeartBeatWorker(SERVICE_NAME,serviceInstanceId,httpSender)).start();

    }
}
